<template>
  <div>
    <el-card shadow="hover">
      <!-- 提交按钮 -->
      <template #header>
        <el-button
          :icon="Plus"
          type="primary"
          @click="showDialog({ tmName: '', logoUrl: '' })"
          >添加</el-button
        >
      </template>

      <!-- 表单 -->
      <el-table :data="tableData" border v-loading="loading">
        <el-table-column type="index" label="序号" width="80" align="center" />
        <el-table-column
          prop="tmName"
          label="品牌名称"
          width="300"
          align="center"
        />
        <el-table-column
          prop="logoUrl"
          label="品牌LOGO"
          align="center"
          width="360"
        >
          <template v-slot="{ row, $index }">
            <el-image :src="row.logoUrl" style="height: 80px"></el-image>
          </template> </el-table-column
        >>
        <el-table-column label="操作">
          <template v-slot="{ row, $index }">
            <el-button
              :icon="Edit"
              type="warning"
              size="small"
              @click="showDialog(row)"
            ></el-button>
            <el-button :icon="Delete" type="danger" size="small"></el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        style="margin-top: 20px"
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[3, 6, 9]"
        layout="prev, pager, next, jumper,->,sizes,total,"
        @size-change="getList"
        @current-change="getList"
      />

      <!-- 对话框 -->
      <el-dialog
        v-model="isShowDialog"
        :title="dialogForm.id ? '修改品牌' : '添加品牌'"
      >
        <el-form
          :model="dialogForm"
          label-width="140px"
          :rules="rules"
          ref="ruleFormRef"
        >
          <el-form-item label="品牌名称" prop="tmName">
            <el-input
              v-model="dialogForm.tmName"
              autocomplete="off"
              style="width: 400px"
              placeholder="请输入品牌名称"
            />
          </el-form-item>
          <el-form-item label="品牌LOGO" prop="logoUrl">
            <el-upload
              class="avatar-uploader"
              :action="`${BASE_URL}/admin/product/fileUpload`"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img
                v-if="dialogForm.logoUrl"
                :src="dialogForm.logoUrl"
                class="avatar"
              />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
              <template #tip>
                <div class="el-upload__tip">
                  只能使用jpg/png格式,并且大小不能超过500kb!
                </div>
              </template>
            </el-upload>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="resetForm(ruleFormRef)">取消</el-button>
            <el-button type="primary" @click="submitForm(ruleFormRef)">
              确认
            </el-button>
          </span>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script lang="ts">
  export default {
    name: "Trademark",
  };
</script>

<script lang="ts" setup>
  import type {
    trademarkItemModel,
    trandemarkListModel,
  } from "@/api/product/model/trademarkModel";
  import {
    AddTrademarkListApi,
    getTrademarkListApi,
    updateTrademarkListApi,
  } from "@/api/product/trademark";
  import { Plus, Delete, Edit } from "@element-plus/icons-vue";
  import {
    ElMessage,
    type FormInstance,
    type FormRules,
    type UploadProps,
  } from "element-plus";
  import { ref, onMounted, reactive } from "vue";

  /* 分页 初始化数据 */
  const tableData = ref<trandemarkListModel>([]);
  const currentPage = ref(1);
  const pageSize = ref(3);
  const total = ref(0);
  const loading = ref(false); // 是否显示loading

  //获取列表数据
  const getList = async () => {
    loading.value = true;
    const result = await getTrademarkListApi(currentPage.value, pageSize.value);
    tableData.value = result.records;
    total.value = result.total;
    loading.value = false;
  };
  //初始化请求
  onMounted(() => {
    getList();
  });

  //对话框
  const isShowDialog = ref(false);
  const dialogForm = reactive<trademarkItemModel>({
    tmName: "",
    logoUrl: "",
  });

  const BASE_URL = import.meta.env.VITE_BASE_URL;

  const handleAvatarSuccess: UploadProps["onSuccess"] = (
    response,
    uploadFile
  ) => {
    // dialogForm.logoUrl = URL.createObjectURL(uploadFile.raw!);
    dialogForm.logoUrl = response.data;
    // 清除logo的错误提示信息
    ruleFormRef.value?.clearValidate(["logoUrl"]);
  };

  const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
    if (rawFile.type !== "image/jpeg" && rawFile.type !== "image/png") {
      ElMessage.error("图片格式必须是jpg或png!");
      return false;
    } else if (rawFile.size / 1024 > 500) {
      ElMessage.error("图片大小不能超过 500KB!");
      return false;
    }
    return true;
  };

  //显示提交或修改成功
  const showDialog = (trademark: trademarkItemModel) => {
    isShowDialog.value = true;
    dialogForm.id = trademark.id;
    dialogForm.tmName = trademark.tmName;
    dialogForm.logoUrl = trademark.logoUrl;

    setTimeout(() => {
      ruleFormRef.value?.clearValidate();
    }, 0);
  };

  //点击提交对话弹窗
  const confirm = async () => {
    if (dialogForm.id) {
      await updateTrademarkListApi(dialogForm);
    } else {
      await AddTrademarkListApi(dialogForm);
    }
    isShowDialog.value = false;
    getList();
    ElMessage.success(`${dialogForm.id ? "修改" : "添加"}成功`);
  };

  //表单验证
  const ruleFormRef = ref<FormInstance>();
  const rules = reactive<FormRules>({
    tmName: [
      { required: true, message: "必须填写品牌名称！", trigger: "blur" },
      { validator: validatePass },
    ],
    logoUrl: [
      {
        required: true,
        message: "必须上传品牌LOGO！",
      },
    ],
  });
  function validatePass(rule: any, value: any, callback: any) {
    if (value.length >= 3 && value.length <= 5) {
      callback();
    } else {
      callback("请写3~5个字的名称！");
    }
  }
  const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    await formEl.validate((valid) => {
      if (valid) {
        confirm();
      }
    });
  };

  const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    formEl.resetFields();
    isShowDialog.value = false;
  };
</script>

<style lang="scss" scoped>
  .avatar-uploader .avatar {
    width: 178px;
    // height: 178px;
    display: block;
  }

  .avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
  }

  .avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
  }

  .el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
  }
</style>
